package com.gujia.interceptor;

import com.gujia.dao.LoginTicketDao;
import com.gujia.dao.UserDao;
import com.gujia.model.LoginTicket;
import com.gujia.model.User;
import com.gujia.util.LoginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by GuJia on 2017/6/26.
 */
@Component
public class PassportInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginTicketDao loginTicketDao;

    @Autowired
    private UserDao userDao;

    //@Autowired
    //private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        String tikcet = null;

        if (httpServletRequest.getCookies() != null) {
            for (Cookie cookie : httpServletRequest.getCookies()) {
                if (cookie.getName().equals("ticket")) {
                    tikcet = cookie.getValue();
                    break;
                }
            }
        }

        if (null != tikcet) {
            LoginTicket loginTicket = loginTicketDao.selectByTicket(tikcet);

            if (null == loginTicket || loginTicket.getExpired().before(new Date()) || !"0".equals(loginTicket.getStatus())) {
                return true;
            }

            User user = userDao.selectById(loginTicket.getUserId());
            //hostHolder.setUser(user);
            LoginUtil.setUser(user);
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null && LoginUtil.getUser() != null) {
            modelAndView.addObject("user", LoginUtil.getUser());
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        LoginUtil.clear();
    }

}


